import { BASE_HTTP_URL } from "@/config/env";
// http 实现类
class HttpImpl {
    request(url: string, data: RequestInit, invoke?: Function, error?: Function): any {
        fetch(BASE_HTTP_URL + url, data)
            .then(response => {
                if (response.ok != true || response.status != 200) {
                    alert("无法获取页面! 错误代码： " + response.status)
                    return;
                }
                return response.json()
            }).then(data => {
                if (invoke != null) {
                    invoke(data)
                }
            })
            .catch((err) => {
                if (error != null) {
                    error(err)
                }
            })
    }
    getImage(url: string,invoke: Function, error?: Function){
        fetch(BASE_HTTP_URL+url, {
            method: 'GET'
        }).then(response=>{
            if (response.ok != true || response.status != 200) {
                alert("无法获取页面! 错误代码： " + response.status)
                return;
            }
            return response.blob()
        }).then(data=>{
            invoke(data)
        }).catch(err=>{
            if(error!=null){
                error(err)
            }
        })
    }
}
// 方法实现类
class MethodImpl {
    GET: string = "GET"
    POST: string = "POST"
    PUT: string = "PUT"
    DELETE: string = "DELETE"
}

// 请求头
class headerImpl {
    content_json(header: any) {
        header["Content-Type"] = "application/json"
    }
}

// 请求类
class FormDataOper{
    initDataFormat(files?: FileList | null, body?: any): FormData {
        let formData = new FormData()
        if(body != null){
            for(let key in body ){
                formData.append(encodeURI(key), body[key])
            }
        }
        if (files != null) {
            for (let i = 0; i < files.length; i++) {
                formData.append(encodeURI(files[i].name), files[i])
            }
        }
        return formData;
    }
    initDataFormatByID(id: string, body?: any): FormData {
        let files: HTMLInputElement = <HTMLInputElement>document.getElementById(id)
        return this.initDataFormat(files.files, body)
    }
}
export const formDataOper = new FormDataOper()
export const method = new MethodImpl()
export const http = new HttpImpl()


